import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets('MNIST_data',one_hot=True)

# 输入图片
n_inputs = 20#一行28个
max_time =28#一共28行
lstm_size = 100# 隐藏单元
n_classes =10 #10个分类
batch_size = 50
n_batch = mnist.train.num_examples // batch_size

#
x = tf.placeholder(tf.float32,[None,784])
y = tf.placeholder(tf.float32,[None,10])

weight = tf.Variable(tf.truncated_normal([lstm_size,n_classes],stddev=0.1))
biases = tf.Variable(tf.constant(0.1,shape=[n_classes]))

def RNN(X,weights,biases):
    inputs =tf.reshape(X,[-1,max_time,n_inputs])
    # 定义LSTM基本CELL
    # ----------------------------------无法运行---------------------------------------------------
    # lstm_cell = core_run_cell.BasicLSTMCell(lstm_size)
    lstm_cell = tf.contrib.rnn.core_run_cell.BasicLSTMCell(lstm_size)
    outputs,final_state = tf.nn.dynamic_rnn(lstm_cell,inputs,dtype=tf.float32)
    results = tf.matmul(final_state[1],weights)+biases
    return results

prediction = RNN(x,weight,biases)

cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction))

# Adam
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

# 结果放在布尔列表
correct_prediction = tf.equal(tf.argmax(prediction,1),tf.argmax(y,1))

accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for epoch in range(6):
        for batch in range(n_batch):
            batch_xs,batch_ys = mnist.train.next_batch(batch_size)
            sess.run(train_step,feed_dict={x:batch_xs,y:batch_ys})

        acc = sess.run(accuracy,feed_dict={x: mnist.train.images, y: mnist.train.labels})
        print('Iter' + str(epoch) + ',Testing Accuracy:' + str(acc) )
